package cn.kgc.spring.factory;


import cn.kgc.spring.dao.StudentDaoImp;
import cn.kgc.spring.entity.Student;

import java.lang.reflect.Constructor;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.ResourceBundle;

/**
 * @author: mosin
 * @version: v1.0  2022/4/21
 * 创建
 * 1.对象的工厂
 * 2.反射
 * 3.配置文件  xml  dom4j
 *  spring   ioc     控制反转    将对象的创建交于工厂创建
 */
public class BeanFactory {
    private static HashMap<String,Object> beans= new HashMap<>();
    public  BeanFactory(String path){
        ResourceBundle bundle = ResourceBundle.getBundle(path);
        Enumeration<String> keys = bundle.getKeys();
        while (keys.hasMoreElements()){
            String key = keys.nextElement();
            String className = bundle.getString(key);
            try {
                Class clazz= Class.forName(className);
                Constructor constructor = clazz.getDeclaredConstructor();
                Object o = constructor.newInstance();
                beans.put(key, o);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public  <T>  T getBean(String key,Class<T> clazz){  //Student.class   T ->Student
        return   clazz.cast(beans.get(key)) ;
    }


    public static void main(String[] args) {
        BeanFactory factory = new BeanFactory("bean");
        Student student = factory.getBean("student", Student.class);
        System.out.println("student = " + student);
    }
}
